package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// MiniprogramConfig 小程序配置模型
type MiniprogramConfig struct {
	BaseModel
	// 基础配置
	AppID          string `orm:"size(100)" json:"app_id"`
	AppSecret      string `orm:"size(100)" json:"app_secret"`
	Name           string `orm:"size(100)" json:"name"`
	Logo           string `orm:"size(255)" json:"logo"`
	Description    string `orm:"size(500)" json:"description"`
	WelcomeMessage string `orm:"size(500)" json:"welcome_message"`
	ServicePhone   string `orm:"size(20)" json:"service_phone"`
	ServiceTime    string `orm:"size(100)" json:"service_time"`
	IsOpen         int8   `orm:"default(1)" json:"is_open"` // 1:开启, 0:关闭

	// 支付配置
	MchId  string `orm:"size(100)" json:"mch_id"`
	MchKey string `orm:"size(100)" json:"mch_key"`
	//支付证书序列号
	CertSerialNo string `orm:"size(100)" json:"cert_serial_no"`
	KeyFile      string `orm:"size(255)" json:"key_file"`
	CertFile     string `orm:"size(255)" json:"cert_file"`
	NotifyUrl    string `orm:"size(255)" json:"notify_url"`

	// 分享设置
	ShareTitle       string `orm:"size(100)" json:"share_title"`
	ShareImage       string `orm:"size(255)" json:"share_image"`
	ShareDescription string `orm:"size(500)" json:"share_description"`

	// 公告设置
	NoticeEnabled int8   `orm:"default(1)" json:"notice_enabled"` // 1:开启, 0:关闭
	NoticeTitle   string `orm:"size(100)" json:"notice_title"`
	NoticeContent string `orm:"size(1000)" json:"notice_content"`

	// 协议设置
	PrivacyPolicy string `orm:"type(text)" json:"privacy_policy"`
	UserAgreement string `orm:"type(text)" json:"user_agreement"`

	// 模板消息
	OrderPayTemplate      string `orm:"size(100)" json:"order_pay_template"`
	OrderShipTemplate     string `orm:"size(100)" json:"order_ship_template"`
	OrderCompleteTemplate string `orm:"size(100)" json:"order_complete_template"`
	CouponTemplate        string `orm:"size(100)" json:"coupon_template"`
}

// TableName 设置表名
func (m *MiniprogramConfig) TableName() string {
	return "ss_miniprogram_config"
}

// GetMiniprogramConfigByAppId 根据AppId获取小程序配置
func GetMiniprogramConfigByAppId(appId string) (*MiniprogramConfig, error) {
	o := orm.NewOrm()
	config := &MiniprogramConfig{}
	err := o.QueryTable(new(MiniprogramConfig)).Filter("is_deleted", 0).Filter("AppID", appId).One(config)
	if err != nil {
		if err == orm.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}
	return config, nil
}

// GetMiniprogramConfig 获取小程序配置
func GetMiniprogramConfig(app_id string) (*MiniprogramConfig, error) {
	o := orm.NewOrm()
	config := &MiniprogramConfig{}

	// 尝试获取第一条记录
	err := o.QueryTable(new(MiniprogramConfig)).Filter("is_deleted", 0).Filter("AppID", app_id).One(config)

	// 如果没有记录，创建一个默认配置
	if err == orm.ErrNoRows {
		config = &MiniprogramConfig{
			Name:           "超级共享空间",
			Description:    "共享娱乐场所预约平台",
			WelcomeMessage: "欢迎使用超级共享空间",
			IsOpen:         1,
			NoticeEnabled:  0,
		}

		_, err = o.Insert(config)
		return config, err
	}

	return config, err
}

// GetMiniprogramConfigByFranchiseId 获取小程序配置
func GetMiniprogramConfigByFranchiseId(franchise_id int64) (*MiniprogramConfig, error) {
	o := orm.NewOrm()
	config := &MiniprogramConfig{}
	config.FranchiseId = franchise_id
	// 尝试获取第一条记录
	err := o.QueryTable(new(MiniprogramConfig)).Filter("is_deleted", 0).Filter("franchise_id", franchise_id).One(config)

	// 如果没有记录，创建一个默认配置
	if err == orm.ErrNoRows {
		config = &MiniprogramConfig{
			Name:           "超级共享空间",
			Description:    "共享娱乐场所预约平台",
			WelcomeMessage: "欢迎使用超级共享空间",
			IsOpen:         1,
			NoticeEnabled:  0,
		}

		_, err = o.Insert(config)
		return config, err
	}

	return config, err
}

// UpdateMiniprogramConfig 更新小程序配置
func UpdateMiniprogramConfig(config *MiniprogramConfig) error {
	o := orm.NewOrm()

	// 检查是否存在记录
	exist := &MiniprogramConfig{}
	err := o.QueryTable(new(MiniprogramConfig)).Filter("is_deleted", 0).Filter("franchise_id", config.FranchiseId).One(exist)

	// 如果不存在，则创建
	if err == orm.ErrNoRows {
		config.BeforeInsert()
		_, err = o.Insert(config)
		return err
	}

	// 如果存在，则只更新非空字段
	config.Id = exist.Id

	// 使用反射获取结构体字段值，只更新非空字段
	fields := []string{}

	// 基础配置
	if config.AppID != "" {
		fields = append(fields, "AppID")
	}
	if config.AppSecret != "" {
		fields = append(fields, "AppSecret")
	}
	if config.Name != "" {
		fields = append(fields, "Name")
	}
	if config.Logo != "" {
		fields = append(fields, "Logo")
	}
	if config.Description != "" {
		fields = append(fields, "Description")
	}
	if config.WelcomeMessage != "" {
		fields = append(fields, "WelcomeMessage")
	}
	if config.ServicePhone != "" {
		fields = append(fields, "ServicePhone")
	}
	if config.ServiceTime != "" {
		fields = append(fields, "ServiceTime")
	}
	// IsOpen是布尔值，总是更新
	fields = append(fields, "IsOpen")

	// 支付配置
	if config.MchId != "" {
		fields = append(fields, "MchId")
	}
	if config.MchKey != "" {
		fields = append(fields, "MchKey")
	}
	if config.CertSerialNo != "" {
		fields = append(fields, "CertSerialNo")
	}
	if config.CertFile != "" {
		fields = append(fields, "CertFile")
	}
	if config.KeyFile != "" {
		fields = append(fields, "KeyFile")
	}
	if config.NotifyUrl != "" {
		fields = append(fields, "NotifyUrl")
	}

	// 分享设置
	if config.ShareTitle != "" {
		fields = append(fields, "ShareTitle")
	}
	if config.ShareImage != "" {
		fields = append(fields, "ShareImage")
	}
	if config.ShareDescription != "" {
		fields = append(fields, "ShareDescription")
	}

	// 公告设置
	// NoticeEnabled是布尔值，总是更新
	fields = append(fields, "NoticeEnabled")
	if config.NoticeTitle != "" {
		fields = append(fields, "NoticeTitle")
	}
	if config.NoticeContent != "" {
		fields = append(fields, "NoticeContent")
	}

	// 协议设置
	if config.PrivacyPolicy != "" {
		fields = append(fields, "PrivacyPolicy")
	}
	if config.UserAgreement != "" {
		fields = append(fields, "UserAgreement")
	}

	// 模板消息
	if config.OrderPayTemplate != "" {
		fields = append(fields, "OrderPayTemplate")
	}
	if config.OrderShipTemplate != "" {
		fields = append(fields, "OrderShipTemplate")
	}
	if config.OrderCompleteTemplate != "" {
		fields = append(fields, "OrderCompleteTemplate")
	}
	if config.CouponTemplate != "" {
		fields = append(fields, "CouponTemplate")
	}

	// 添加更新时间字段
	fields = append(fields, "UpdatedAt")

	// 如果没有字段需要更新，直接返回
	if len(fields) <= 1 { // 只有UpdatedAt
		return nil
	}

	_, err = o.Update(config, fields...)
	return err
}
